using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Lzfy_Refund_Service.Models;
using Lzfy_Refund_Service.Services;

namespace Lzfy_Refund_Service.Controllers
{
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    public class UserController : ControllerBase
    {
        private readonly IUserManagementService _userManagementService;
        private readonly ILogger<UserController> _logger;

        public UserController(IUserManagementService userManagementService, ILogger<UserController> logger)
        {
            _userManagementService = userManagementService;
            _logger = logger;
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        [HttpPost("list")]
        public async Task<IActionResult> GetUserList([FromBody] UserListRequest request)
        {
            try
            {
                var result = await _userManagementService.GetUserListAsync(request);
                return Ok(new { success = true, data = result });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户列表失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 根据ID获取用户详情
        /// </summary>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetUserById(int id)
        {
            try
            {
                var user = await _userManagementService.GetUserByIdAsync(id);
                if (user == null)
                {
                    return NotFound(new { success = false, message = "用户不存在" });
                }
                return Ok(new { success = true, data = user });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户详情失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 创建用户
        /// </summary>
        [HttpPost]
        public async Task<IActionResult> CreateUser([FromBody] UserDto userDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { success = false, message = "参数验证失败", errors = ModelState });
                }

                var userId = await _userManagementService.CreateUserAsync(userDto);
                return Ok(new { success = true, data = new { id = userId }, message = "用户创建成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建用户失败");
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 更新用户
        /// </summary>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateUser(int id, [FromBody] UserDto userDto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new { success = false, message = "参数验证失败", errors = ModelState });
                }

                var result = await _userManagementService.UpdateUserAsync(id, userDto);
                if (result)
                {
                    return Ok(new { success = true, message = "用户更新成功" });
                }
                return BadRequest(new { success = false, message = "用户更新失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新用户失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 删除用户
        /// </summary>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteUser(int id)
        {
            try
            {
                var result = await _userManagementService.DeleteUserAsync(id);
                if (result)
                {
                    return Ok(new { success = true, message = "用户删除成功" });
                }
                return BadRequest(new { success = false, message = "用户删除失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除用户失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 切换用户状态
        /// </summary>
        [HttpPost("{id}/toggle-status")]
        public async Task<IActionResult> ToggleUserStatus(int id, [FromBody] ToggleStatusRequest request)
        {
            try
            {
                var result = await _userManagementService.ToggleUserStatusAsync(id, request.IsActive);
                if (result)
                {
                    return Ok(new { success = true, message = "用户状态更新成功" });
                }
                return BadRequest(new { success = false, message = "用户状态更新失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "切换用户状态失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 重置用户密码
        /// </summary>
        [HttpPost("{id}/reset-password")]
        public async Task<IActionResult> ResetUserPassword(int id, [FromBody] ResetPasswordRequest request)
        {
            try
            {
                var result = await _userManagementService.ResetUserPasswordAsync(id, request.NewPassword);
                if (result)
                {
                    return Ok(new { success = true, message = "密码重置成功" });
                }
                return BadRequest(new { success = false, message = "密码重置失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重置用户密码失败，ID: {Id}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 分配用户角色
        /// </summary>
        [HttpPost("{id}/roles")]
        public async Task<IActionResult> AssignUserRoles(int id, [FromBody] List<int> roleIds)
        {
            try
            {
                var result = await _userManagementService.AssignUserRolesAsync(id, roleIds);
                if (result)
                {
                    return Ok(new { success = true, message = "用户角色分配成功" });
                }
                return BadRequest(new { success = false, message = "用户角色分配失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "分配用户角色失败，用户ID: {UserId}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取用户角色
        /// </summary>
        [HttpGet("{id}/roles")]
        public async Task<IActionResult> GetUserRoles(int id)
        {
            try
            {
                var roles = await _userManagementService.GetUserRolesAsync(id);
                return Ok(new { success = true, data = roles });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户角色失败，用户ID: {UserId}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }

        /// <summary>
        /// 获取用户权限
        /// </summary>
        [HttpGet("{id}/permissions")]
        public async Task<IActionResult> GetUserPermissions(int id)
        {
            try
            {
                var permissions = await _userManagementService.GetUserPermissionsAsync(id);
                return Ok(new { success = true, data = permissions });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取用户权限失败，用户ID: {UserId}", id);
                return BadRequest(new { success = false, message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 重置密码请求模型
    /// </summary>
    public class ResetPasswordRequest
    {
        public string NewPassword { get; set; } = string.Empty;
    }
}